/**
 * @name: comment.controller
 * @data: 2024/6/1 11:34
 */
import {Body, Controller, Get, Inject, Param, Post} from "@midwayjs/core";
import {Context} from "@midwayjs/koa";
import {CommentService} from "../service/comment.service";
import ResultInterface from "../interface/Result";
import {CommentInterface} from "../interface/Comment";
import {Validate} from "@midwayjs/validate";
import {CommentInsertVO} from "../pojo/vo/comment.vo";
import Comment from "../pojo/entity/comment.entity";``
import Result from "../common/Result";
import {HTTP_STATE_CODE} from "../common/const";

@Controller("/comment")
export class CommentController {
  @Inject()
  commentService:CommentService;
  @Inject()
  ctx: Context;

  // @ts-ignore
  /**
   * 新增文章
   */
  @Post("/insert")
  // @ts-ignore
  @Validate(CommentInsertVO)
  async insertComment(@Body() comment:Comment): Promise<ResultInterface<CommentInterface>>{
    try {
      const commentData=CommentInsertVO.parse(comment);
      const result=await this.commentService.insertComment(commentData as Comment);
      if (result) {
        return Result({
          code: HTTP_STATE_CODE.SUCCESS,
          msg: "新增成功",
        });
      } else {
        return Result({
          code: HTTP_STATE_CODE.ERROR,
          msg: "新增失败",
        });
      }
    }catch (e) {
      return  {
        code: HTTP_STATE_CODE.FORBIDDEN,
        msg: "缺少必填字段",
        data: null
      }
    }
  }

  @Get("/article/:articleId")
  async selectArticleByTitle(@Param("articleId") articleId: number): Promise<ResultInterface<Comment>> {
    try {
      const result=await this.commentService.selectCommentListByArticleId(articleId);
      if (result.length > 0) {
        return Result<Comment>({
          code: HTTP_STATE_CODE.SUCCESS,
          msg: "查询成功",
          data: result
        });
      } else {
        return Result<Comment>({
          code: HTTP_STATE_CODE.NO_CONTENT,
          msg: "查询失败",
          data: result
        });
      }
    }catch (e) {
      return Result<any>({
        code: HTTP_STATE_CODE.ERROR,
        msg: "查询失败",
        data: e
      });
    }
  }

}
